<template>
  <div>
    <HeadContainer :title="$t('title.media')" @back="emits('back')" showAdd full @add="toPublish">
      <TopTabs
        v-model="topTabsValue"
        :items="topTabsTypes"
        :item-value="`value`"
        :item-label="`label`"
        class="px-4 mine-media"
      ></TopTabs>
      <MediaWall
        v-model="mediaType"
        :video-data="videoFetcher.dataList.value"
        :photo-data="photoFetcher.dataList.value"
        :video-loading="videoFetcher.loading.value"
        :photo-loading="photoFetcher.loading.value"
        :video-no-more="videoFetcher.noMore.value"
        :photo-no-more="photoFetcher.noMore.value"
        @click:item="onItemClick"
        @intersect="fetcher.nextPage()"
        class="pt-5"
        :scheduled="topTabsValue === FEED_PERMISION.FUTURE"
      ></MediaWall>
    </HeadContainer>
  </div>
</template>

<script setup>
import { computed, onActivated, ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { usePublishStore } from '@/store/publish'
import { toDate, toDateTimeString } from '@/utils/string-helper'
import HeadContainer from '@/components/layout/HeadContainer.vue'
import MediaWall from '@/components/media/MediaWall.vue'
import TopTabs from '@/components/tabs/TopTabs.vue'
import { useInfinite } from '@/compositions/request/infinite'
import { FEED_PERMISION, MEDIA_TYPE } from '@/constant'
import { MEDIA_TYPE as MEDIA_TYPE_PUBLISH } from '@/constant/publish'
import API from '@/http'

const emits = defineEmits(['toPage', 'back'])

const { setPublishParams } = usePublishStore()

const router = useRouter()
function toPublish() {
  router.replace('/publish')
}

const topTabsValue = ref(FEED_PERMISION.ALL)
const topTabsTypes = ref([
  {
    label: 'common.everyone',
    value: FEED_PERMISION.ALL,
  },
  {
    label: 'common.subscriber',
    value: FEED_PERMISION.SUB,
  },
  {
    label: 'common.store',
    value: FEED_PERMISION.SHOP,
  },
  {
    label: 'info.schedulePublish',
    value: FEED_PERMISION.FUTURE,
  },
])

const allMediaType = ref(MEDIA_TYPE.VIDEO)
const allVideoFetcher = useInfinite({
  request: API.Publish.list,
  params: { type: MEDIA_TYPE_PUBLISH.VIDEO, visible: FEED_PERMISION.ALL },
})
const allPhotoFetcher = useInfinite({
  request: API.Publish.list,
  params: { type: MEDIA_TYPE_PUBLISH.IMAGE, visible: FEED_PERMISION.ALL },
})

const subMediaType = ref(MEDIA_TYPE.VIDEO)
const subVideoFetcher = useInfinite({
  request: API.Publish.list,
  params: { type: MEDIA_TYPE_PUBLISH.VIDEO, visible: FEED_PERMISION.SUB },
})
const subPhotoFetcher = useInfinite({
  request: API.Publish.list,
  params: { type: MEDIA_TYPE_PUBLISH.IMAGE, visible: FEED_PERMISION.SUB },
})

const shopMediaType = ref(MEDIA_TYPE.VIDEO)
const shopVideoFetcher = useInfinite({
  request: API.Publish.list,
  params: { type: MEDIA_TYPE_PUBLISH.VIDEO, visible: FEED_PERMISION.SHOP },
})
const shopPhotoFetcher = useInfinite({
  request: API.Publish.list,
  params: { type: MEDIA_TYPE_PUBLISH.IMAGE, visible: FEED_PERMISION.SHOP },
})

const futureMediaType = ref(MEDIA_TYPE.VIDEO)
// 參數要給一個當下的 local_time 一開始建立好的話，等到觸發 tab 才 init 會有時間計算錯誤的問題...
let futureVideoFetcher
let futurePhotoFetcher

// top tabs 初次切換才 init fetcher
const topTabsTriggered = {
  all: false,
  sub: false,
  shop: false,
  future: false,
}
watch(
  topTabsValue,
  (v) => {
    switch (v) {
      case FEED_PERMISION.ALL:
        if (!topTabsTriggered.all) {
          topTabsTriggered.all = true
          allVideoFetcher.init()
          allPhotoFetcher.init()
        }
        break
      case FEED_PERMISION.SUB:
        if (!topTabsTriggered.sub) {
          topTabsTriggered.sub = true
          subVideoFetcher.init()
          subPhotoFetcher.init()
        }
        break
      case FEED_PERMISION.SHOP:
        if (!topTabsTriggered.shop) {
          topTabsTriggered.shop = true
          shopVideoFetcher.init()
          shopPhotoFetcher.init()
        }
        break
      case FEED_PERMISION.FUTURE:
        if (!topTabsTriggered.future) {
          topTabsTriggered.future = true
          futureVideoFetcher = useInfinite({
            request: API.Publish.list,
            params: { type: MEDIA_TYPE_PUBLISH.VIDEO, local_time: toDateTimeString(new Date()) },
          })
          futurePhotoFetcher = useInfinite({
            request: API.Publish.list,
            params: { type: MEDIA_TYPE_PUBLISH.IMAGE, local_time: toDateTimeString(new Date()) },
          })
          futureVideoFetcher.init()
          futurePhotoFetcher.init()
        }
        break
    }
  },
  { immediate: true },
)

const mediaType = computed({
  get() {
    switch (topTabsValue.value) {
      case FEED_PERMISION.ALL:
        return allMediaType.value
      case FEED_PERMISION.SUB:
        return subMediaType.value
      case FEED_PERMISION.SHOP:
        return shopMediaType.value
      case FEED_PERMISION.FUTURE:
        return futureMediaType.value
      default:
        return allMediaType.value
    }
  },
  set(v) {
    switch (topTabsValue.value) {
      case FEED_PERMISION.ALL:
        allMediaType.value = v
        break
      case FEED_PERMISION.SUB:
        subMediaType.value = v
        break
      case FEED_PERMISION.SHOP:
        shopMediaType.value = v
        break
      case FEED_PERMISION.FUTURE:
        futureMediaType.value = v
        break
      default:
        allMediaType.value = v
        break
    }
  },
})

const videoFetcher = computed(() => {
  switch (topTabsValue.value) {
    case FEED_PERMISION.ALL:
      return allVideoFetcher
    case FEED_PERMISION.SUB:
      return subVideoFetcher
    case FEED_PERMISION.SHOP:
      return shopVideoFetcher
    case FEED_PERMISION.FUTURE:
      return futureVideoFetcher
    default:
      return allVideoFetcher
  }
})
const photoFetcher = computed(() => {
  switch (topTabsValue.value) {
    case FEED_PERMISION.ALL:
      return allPhotoFetcher
    case FEED_PERMISION.SUB:
      return subPhotoFetcher
    case FEED_PERMISION.SHOP:
      return shopPhotoFetcher
    case FEED_PERMISION.FUTURE:
      return futurePhotoFetcher
    default:
      return allPhotoFetcher
  }
})
const fetcher = computed(() => {
  if (mediaType.value === MEDIA_TYPE.VIDEO) {
    return videoFetcher.value
  } else if (mediaType.value === MEDIA_TYPE.PHOTO) {
    return photoFetcher.value
  } else {
    return null
  }
})

function onItemClick(index) {
  const {
    id,
    type,
    shape,
    content,
    tags,
    attribute,
    visible,
    money,
    display_at,
    img_path: imgPath,
    img_width: imgWidth,
    img_height: imgHeight,
    img_more: imgMore,
    video_path: videoPath,
    video_time: videoTime,
    slice,
  } = fetcher.value.dataList.value[index]

  const postTime = toDate(display_at)

  setPublishParams({
    id,
    type,
    shape,
    content,
    tags,
    attribute,
    visible,
    money,
    postTime: postTime > new Date() ? postTime : null,
    imgPath,
    imgWidth,
    imgHeight,
    imgMore,
    videoPath,
    videoTime,
    slice,
  })
  router.replace({ name: 'publish' })
}

// 每次回來可能都會有資料被改變的情況，refresh 重新拿才會是最新的
onActivated(() => {
  if (topTabsTriggered.all) {
    allVideoFetcher.refresh()
    allPhotoFetcher.refresh()
  }

  if (topTabsTriggered.sub) {
    subVideoFetcher.refresh()
    subPhotoFetcher.refresh()
  }

  if (topTabsTriggered.shop) {
    shopVideoFetcher.refresh()
    shopPhotoFetcher.refresh()
  }

  if (topTabsTriggered.future) {
    futureVideoFetcher.refresh({
      newParams: { type: MEDIA_TYPE_PUBLISH.VIDEO, local_time: toDateTimeString(new Date()) },
    })
    futurePhotoFetcher.refresh({
      newParams: { type: MEDIA_TYPE_PUBLISH.IMAGE, local_time: toDateTimeString(new Date()) },
    })
  }
})
</script>
